<template>
  <div class="news-edit">
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑消息' : '发布消息'"
      width="700px"
      :before-close="handleClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="news-form"
      >
        <el-form-item label="消息标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入消息标题" />
        </el-form-item>

        <el-form-item label="消息描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="6"
            placeholder="请输入消息描述"
          />
        </el-form-item>

        <el-form-item label="消息图片">
          <UploadFile
            v-model="form.image"
            action="/api/upload"
            :limit="1"
            :file-size="5"
            @success="handleUploadSuccess"
          />
          <div class="upload-tip">建议上传比例为16:9的图片，大小不超过2MB</div>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import UploadFile from "@/components/UploadFile.vue";

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  editData: {
    type: Object,
    default: () => null,
  },
});

const emit = defineEmits(["update:visible", "submit", "cancel"]);

// 对话框显示状态
const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit("update:visible", val),
});

// 是否为编辑模式
const isEdit = computed(() => !!props.editData);

// 表单引用
const formRef = ref(null);

// 表单数据
const form = reactive({
  title: "",
  description: "",
  image: [
    "https://img-lang.55sld.com/channel1langimages/seller/goods/ZScpQ4FYJscQXRSuxtl.png",
  ],
});

// 重置表单 - 确保函数定义在使用之前
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }

  // 重置为初始值
  Object.assign(form, {
    title: "",
    description: "",
    image: "",
  });
};

// 表单验证规则
const rules = reactive({
  title: [
    { required: true, message: "请输入消息标题", trigger: "blur" },
    { max: 50, message: "标题长度不能超过50个字符", trigger: "blur" },
  ],
  description: [
    { required: true, message: "请输入消息描述", trigger: "blur" },
    { max: 500, message: "描述长度不能超过500个字符", trigger: "blur" },
  ],
});

// 监听编辑数据变化
watch(
  () => props.editData,
  (newVal) => {
    if (newVal) {
      // 编辑模式，填充表单数据
      Object.keys(form).forEach((key) => {
        form[key] = newVal[key] !== undefined ? newVal[key] : form[key];
      });
    } else {
      // 新增模式，重置表单
    //   resetForm();
    }
  },
  { immediate: true, deep: true }
);

// 关闭对话框
const handleClose = () => {
  if (form.title || form.description || form.image) {
    ElMessageBox.confirm("确认关闭？未保存的数据将会丢失", "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        dialogVisible.value = false;
        emit("cancel");
        resetForm();
      })
      .catch(() => {
        // 取消关闭
      });
  } else {
    dialogVisible.value = false;
    emit("cancel");
  }
};

// 提交表单
const submitForm = () => {
  if (!formRef.value) return;

  formRef.value.validate((valid) => {
    if (valid) {
      // 提交表单数据
      const submitData = { ...form };

      // 如果是编辑模式，保留原有ID
      if (isEdit.value && props.editData) {
        submitData.id = props.editData.id;
      }

      emit("submit", submitData);
      dialogVisible.value = false;
      resetForm();
    } else {
      ElMessage.error("请填写必填项");
      return false;
    }
  });
};

const handleUploadSuccess = (response) => {
  console.log(response);
};
</script>

<style scoped lang="scss">
.news-edit {
  .news-form {
    max-height: 65vh;
    overflow-y: auto;
    padding: 0 15px;
  }

  .news-uploader {
    width: 120px;
    height: 120px; // 16:9比例
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: border-color 0.3s;

    &:hover {
      border-color: #409eff;
    }

    .news-image {
      width: 100%;
      height: 100%;
      object-fit: cover;
      display: block;
    }

    .news-uploader-placeholder {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      height: 100%;
      color: #8c939d;

      .uploader-icon {
        font-size: 28px;
        margin-bottom: 8px;
      }
    }
  }

  .upload-tip {
    font-size: 12px;
    color: #606266;
    margin-top: 5px;
  }

  .dialog-footer {
    text-align: right;
  }
}
</style>
